package logcollector

import (
	"github.com/jeromer/syslogparser/rfc3164"
	"time"
	"fmt"
	"errors"
	"cloud_worm/util/proto/ujson"
)

func SyslogParser(buff []byte, l *LogInfo) error {

	p := rfc3164.NewParser(buff)
	if err := p.Parse(); err != nil {
		return err
	}
	info := p.Dump()
	l.HostName = info["hostname"].(string)
	l.ProgramName = info["tag"].(string)
	l.Log = info["content"].(string)
	l.StartTime = info["timestamp"].(time.Time).Format("2006-01-02 15:04:05")
	l.IP = LocalIP						// 记录下本地的ip地址

	return nil
}

var noNeedAnalyzerErr = errors.New("no need analyzer")
func MessageParser(buff []byte, l *LogInfo) error {
	p := rfc3164.NewParser(buff)
	if err := p.Parse(); err != nil {
		return err
	}
	info := p.Dump()
	l.ProgramName = info["tag"].(string)
	if l.ProgramName != "su" {
		return noNeedAnalyzerErr
	}

	l.HostName = info["hostname"].(string)
	l.Log = info["content"].(string)
	l.StartTime = info["timestamp"].(time.Time).Format("2006-01-02 15:04:05")
	l.IP = LocalIP						// 记录下本地的ip地址

	return nil
}

// 解析器的池子
var parserMap map[string]func(buff []byte, l *LogInfo) error

func init()  {
	parserMap = make(map[string]func(buff []byte, l *LogInfo) error)
	RegisterParser(ujson.SysLogLogParser, SyslogParser)				// system parser注册
	RegisterParser(ujson.MessageLogParser, MessageParser)			// message parser注册
}

// 注册解析器
func RegisterParser(name string, parser func(buff []byte, l *LogInfo) error)  {
	if _, exist := parserMap[name]; exist {
		panic(fmt.Sprintf("parser already register for name: %s", name))
	}

	parserMap[name] = parser
	return
}

// 执行解析器
func ExecLogParser(name string, buff []byte, l *LogInfo) error {
	if _, exist := parserMap[name]; exist == false {
		return fmt.Errorf("no parser for '%s'", name)
	}

	return parserMap[name](buff, l)
}

